package com.framework.loippi.utils;

import net.sf.json.JSONObject;
import org.apache.commons.net.util.Base64;

import javax.net.ssl.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;


public class IOSPayVerifyUtils {
    private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    public static final String url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
    public static final String url_verify = "https://buy.itunes.apple.com/verifyReceipt";


    /**
     * 苹果服务器验证
     *
     * @param receipt 账单
     * @return null 或返回结果
     * 沙盒   https://sandbox.itunes.apple.com/verifyReceipt
     * @url 要验证的地址
     */
    public static String buyAppVerify(String receipt, String verifyState) {
        String url = url_verify;
        if (verifyState != null && verifyState.equals("Sandbox")) {
            url = url_sandbox;
        }
        String buyCode = getBASE64(receipt);

        System.err.println("buyCode==" + buyCode);
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL console = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "text/json");
            conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            BufferedOutputStream hurlBufOus = new BufferedOutputStream(conn.getOutputStream());

            String str = String.format(Locale.CHINA, "{\"receipt-data\":\"" + buyCode + "\"}");
            hurlBufOus.write(str.getBytes());
            hurlBufOus.flush();

            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            return sb.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 根据原始收据返回苹果的验证地址:
     * * 沙箱    https://sandbox.itunes.apple.com/verifyReceipt
     * 真正的地址   https://buy.itunes.apple.com/verifyReceipt
     *
     * @param receipt
     * @return Sandbox 测试单   Real 正式单
     */
    public static String getEnvironment(String receipt) {
        try {
            JSONObject job = JSONObject.fromObject(receipt);
            if (job.containsKey("environment")) {
                String evvironment = job.getString("environment");
                return evvironment;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "Real";
    }

    /**
     * 用BASE64加密
     *
     * @param str
     * @return
     */
    public static String getBASE64(String str) {
        byte[] b = str.getBytes();
        String s = null;
        if (b != null) {
            s = new Base64().encodeToString(b);
        }
        return s;
    }

    /**
     * 解密BASE64字窜
     *
     * @param s
     * @return
     */
    public static String getFromBASE64(String s) {
        byte[] b = null;
        if (s != null) {
            Base64 decoder = new Base64();
            try {
                b = decoder.decode(s);
                return new String(b);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new String(b);
    }

    /**
     * md5加密方法
     *
     * @param plainText 加密字符串
     * @return String 返回32位md5加密字符串(16位加密取substring(8,24))
     * 每位工程师都有保持代码优雅的义务
     * each engineer has a duty to keep the code elegant
     * @author: zhengsunlei
     * Jul 30, 2010 4:38:28 PM
     */
    public final static String md5(String plainText) {
        // 返回字符串
        String md5Str = null;
        try {
            // 操作字符串
            StringBuffer buf = new StringBuffer();
            /**
             * MessageDigest 类为应用程序提供信息摘要算法的功能，如 MD5 或 SHA 算法。
             * 信息摘要是安全的单向哈希函数，它接收任意大小的数据，并输出固定长度的哈希值。
             *
             * MessageDigest 对象开始被初始化。
             * 该对象通过使用 update()方法处理数据。
             * 任何时候都可以调用 reset()方法重置摘要。
             * 一旦所有需要更新的数据都已经被更新了，应该调用digest()方法之一完成哈希计算。
             *
             * 对于给定数量的更新数据，digest 方法只能被调用一次。
             * 在调用 digest 之后，MessageDigest 对象被重新设置成其初始状态。
             */
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 添加要进行计算摘要的信息,使用 plainText 的 byte 数组更新摘要。
            md.update(plainText.getBytes());
            // 计算出摘要,完成哈希计算。
            byte b[] = md.digest();
            int i;
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                // 将整型 十进制 i 转换为16位，用十六进制参数表示的无符号整数值的字符串表示形式。
                buf.append(Integer.toHexString(i));
            }
            // 32位的加密
            md5Str = buf.toString();
            // 16位的加密
            // md5Str = buf.toString().md5Strstring(8,24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5Str;
    }

    /**
     * 客户端向服务器验证
     * <p>
     * <p>
     * * checkState  A  验证成功有效(返回收据)
     * B  账单有效，但己经验证过
     * C  服务器数据库中没有此账单(无效账单)
     * D  不处理
     *
     * @return
     * @throws IOException
     */
//    public void IOSVerify() throws IOException  
//    {  
//          
//        HttpServletRequest request=ServletActionContext.getRequest();  
//        HttpServletResponse response=ServletActionContext.getResponse();  
//        System.out.println(new  Date().toLocaleString()+"  来自苹果端的验证...");  
//        //苹果客户端传上来的收据,是最原据的收据  
//        String receipt=request.getParameter("receipt");  
//        System.out.println(receipt);  
//        //拿到收据的MD5  
//        String md5_receipt=MD5.md5Digest(receipt);  
//        //默认是无效账单  
//        String result=R.BuyState.STATE_C+"#"+md5_receipt;  
//        //查询数据库，看是否是己经验证过的账号  
//        boolean isExists=DbServiceImpl_PNM.isExistsIOSReceipt(md5_receipt);  
//        String verifyResult=null;  
//        if(!isExists){  
//            String verifyUrl=IOS_Verify.getVerifyURL();  
//            verifyResult=IOS_Verify.buyAppVerify(receipt, verifyUrl);  
//            //System.out.println(verifyResult);  
//            if(verifyResult==null){  
//                //苹果服务器没有返回验证结果  
//                result=R.BuyState.STATE_D+"#"+md5_receipt;  
//            }else{  
//                //跟苹果验证有返回结果------------------  
//                JSONObject job = JSONObject.fromObject(verifyResult);  
//                String states=job.getString("status");  
//                if(states.equals("0"))//验证成功  
//                {  
//                    String r_receipt=job.getString("receipt");  
//                    JSONObject returnJson = JSONObject.fromObject(r_receipt);  
//                    //产品ID  
//                    String product_id=returnJson.getString("product_id");  
//                    //数量  
//                    String quantity=returnJson.getString("quantity");  
//                    //跟苹果的服务器验证成功  
//                    result=R.BuyState.STATE_A+"#"+md5_receipt+"_"+product_id+"_"+quantity;  
//                    //交易日期  
//                    String purchase_date=returnJson.getString("purchase_date");  
//                    //保存到数据库  
//                    DbServiceImpl_PNM.saveIOSReceipt(md5_receipt, product_id, purchase_date, r_receipt);  
//                }else{  
//                    //账单无效  
//                    result=R.BuyState.STATE_C+"#"+md5_receipt;  
//                }  
//                //跟苹果验证有返回结果------------------  
//            }  
//            //传上来的收据有购买信息==end=============  
//        }else{  
//            //账单有效，但己验证过  
//            result=R.BuyState.STATE_B+"#"+md5_receipt;  
//        }  
//        //返回结果  
//        try {  
//            System.out.println("验证结果     "+result);  
//            System.out.println();  
//            response.getWriter().write(result);  
//        } catch (IOException e) {  
//            e.printStackTrace();  
//        }  
//          
//    }  
//}  
    public final static int verifyReceipt(String encodedReceipt, String url_verify) {
        int status = -1;
        System.err.println(" encodedReceipt  =verifyReceipt==" + url_verify);
        //This is the URL of the REST webservice in iTunes App Store
        URL url = null;
        try {
            url = new URL(url_verify);
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //make connection, use post mode
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setAllowUserInteraction(false);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //Encode the binary receipt data into Base 64
        //Here I'm using org.apache.commons.codec.binary.Base64 as an encoder, since commons-codec is already in Grails classpath
        Base64 encoder = new Base64();
        //   encodedReceipt=getFromBASE64(encodedReceipt);
        System.err.println(" encodedReceipt  ===" + encodedReceipt);
        //Create a JSON query object
        //Here I'm using Grails' org.codehaus.groovy.grails.web.json.JSONObject
        Map map = new HashMap();
        map.put("receipt-data", encodedReceipt);
        JSONObject jsonObject = JSONObject.fromObject(map);

        //Write the JSON query object to the connection output stream
        PrintStream ps;
        StringBuffer sb = new StringBuffer();
        try {
            ps = new PrintStream(connection.getOutputStream());
            ps.print(jsonObject.toString());
            ps.close();
            //Call the service
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            //Extract response
            String str;

            while ((str = br.readLine()) != null) {
                sb.append(str);

            }
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String response = sb.toString();
        System.err.println(" response  ===" + response);
        //Deserialize response
        JSONObject result = JSONObject.fromObject(response);
        status = result.getInt("status");
        if (status == 0) {
            //provide content
        } else {
            status = -1;
        }

        return status;


    }

    public static void main(String[] args) {
        String encodedReceipt = "ewoJInNpZ25hdHVyZSIgPSAiQW5DZzc2UlFFWW42dHhNUU1jU1d0UjhScEQ4ZEtYMTU2RzhBZTBGdlhDTVlHNVc4VVQvRkxzV1JRcXZWWnZXWFV1eEt2dThrSVBaaW1jSHR4dlVpMEFmOTI2MDRVZ2grNWd0alBUbUltd0wvdXBZb0VyWC9pMUxXSE1DODNjWmJrenFUbHFqQWhqcnQ2dFBxdlRDcTdTVmQ5NzBDVUdSOTREaDBRTGdHa1N3UkFBQURWekNDQTFNd2dnSTdvQU1DQVFJQ0NCdXA0K1BBaG0vTE1BMEdDU3FHU0liM0RRRUJCUVVBTUg4eEN6QUpCZ05WQkFZVEFsVlRNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVNZd0pBWURWUVFMREIxQmNIQnNaU0JEWlhKMGFXWnB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